package com.hc.springbootredis.service.impl;

import com.hc.springbootredis.entity.Comment;
import com.hc.springbootredis.repository.CommentRepository;
import com.hc.springbootredis.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

//@CacheConfig(cacheNames = "comment") //抽离相同的命名空间
@Service("CommentService1")
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentRepository commentRepository;

    /**
     * @Cacheable //查询触发缓存
     * 1.先查有没有缓存，有直接返回，没有查数据库
     * 2.查询数据库，返回结果，并缓存结果
     */
//    @Cacheable(cacheNames = "t_comment") //缓存返回值至命名空间为"t_comment"的内存区
    @Override
    @Cacheable(cacheNames = "comment",unless = "#result==null") //未指定id则默认使用参数值
    public Comment findById(int id) {
        Optional<Comment> optional = commentRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * @CachePut //更新触发缓存
     * 1.先执行方法，再将结果更新至缓存
     */
//    @CachePut
    @CachePut(cacheNames = "comment",key = "#result.id")
    @Override
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }

    /**
     * @CacheEvict  //删除触发缓存
     * 1.先执行方法，再删除缓存
     */
//    @CacheEvict
    @CacheEvict(cacheNames = "comment")
    @Override
    public void deleteById(int id) {
        commentRepository.deleteById(id);
    }
}
